#ifndef __DBMANAGER_H__
#define __DBMANAGER_H__

namespace SPlayerServer
{
    using namespace System;
    using namespace System::Data;
    using namespace System::Data::SqlClient;
    using namespace System::Collections::Generic;
    ref class SqlConnectionGuard
    {
    public:
        SqlConnectionGuard(SqlConnection ^conn) : connection(conn)
        { }
        ~SqlConnectionGuard()
        {
            if (connection)
            {
                connection->Close();
                delete connection;
                connection = nullptr;
            }
        }
    private:
        SqlConnection ^connection;
    };
    ref class Record
    {
    public:
        String ^title;
        String ^filepath;
        unsigned playLength;
        unsigned fileSize;
        bool hasLyric;
        String ^lyricPath;
    };
    ref class DBManager
    {
    public:
        enum class LoginType
        {
            Windows,
            SQL
        };
    public:
        DBManager();
        static void init();
        static void insert(Record ^record);
        static List<Record ^> ^query(String ^titleQueryString);
        static Record ^ getMusic(String ^title);


        //--------------------------------------
        static String ^encodeText(String ^text)
        {
            System::Text::StringBuilder b;
            for each (auto c in System::Text::Encoding::Unicode->GetBytes(text))
            {
                b.AppendFormat("{0:X2}", c);
            }
            return b.ToString();
        }

        static String ^decodeText(String ^text)
        {
            auto unicode = gcnew array<unsigned char>((text->Length + 1) / 2);
            for (int i = 0, n = unicode->Length; i < n; i++)
            {
                unicode[i] = Convert::ToByte(text->Substring(i * 2, 2), 16);
            }
            return System::Text::Encoding::Unicode->GetString(unicode);
        }

        static String ^getConnectionString()
        {
            return loginType == LoginType::Windows ? getSSPIString() : getClassicalString(username, password);
        }
        static String ^getSSPIString()
        {
            return L"Pooling=True;Min Pool Size=10;Max Pool Size=100;Integrated Security=SSPI;Persist Security Info=False;Data Source=localhostt";
        }
        static String ^getClassicalString(String ^username, String ^password)
        {
            return String::Format(L"Pooling=True;Min Pool Size=10;Max Pool Size=100;Persist Security Info = True;User ID = {0};Password = {1};Data Source = localhost",
                                  username, password);
        }
    private:
        static String ^username = "sa";
        static String ^password = "123456";
        static LoginType loginType = LoginType::SQL;
    };
}

#endif // __DBMANAGER_H__